package main

import (
	"embed"
	_ "embed"
	"fmt"
	"log"
	"os"
	"slapp3/backend"

	"github.com/spf13/cobra"
	"github.com/wailsapp/wails/v3/pkg/application"
	"github.com/wailsapp/wails/v3/pkg/events"
)

// Wails uses Go's `embed` package to embed the frontend files into the binary.
// Any files in the frontend/dist folder will be embedded into the binary and
// made available to the frontend.
// See https://pkg.go.dev/embed for more information.

//go:embed all:frontend/dist
var assets embed.FS

//go:embed all:frontend/src/assets
var iconFS embed.FS

var Version string = "0.1.0"

// main function serves as the application's entry point. It initializes the application, creates a window,
// and starts a goroutine that emits a time-based event every second. It subsequently runs the application and
// logs any error that might occur.
func Desktop() {
	appSev := backend.NewApp(Version)

	// 解决 Windows COM 初始化问题
	// if runtime.GOOS == "windows" {
	// 	initWindowsCOM()
	// 	defer uninitWindowsCOM()
	// }

	// Create a new Wails application by providing the necessary options.
	// Variables 'Name' and 'Description' are for application metadata.
	// 'Assets' configures the asset server with the 'FS' variable pointing to the frontend files.
	// 'Bind' is a list of Go struct instances. The frontend has access to the methods of these instances.
	// 'Mac' options tailor the application when running an macOS.
	app := application.New(application.Options{
		Name:        "slapp3",
		Description: "A Secure Link client",
		Services: []application.Service{
			application.NewService(appSev),
			application.NewService(appSev.GetNotifier()),
		},
		Assets: application.AssetOptions{
			Handler: application.AssetFileServerFS(assets),
		},
		Mac: application.MacOptions{
			ApplicationShouldTerminateAfterLastWindowClosed: true,
		},
	})
	appSev.PrepareNotification()
	appSev.SetupNotificationHandlers(app)
	// 托盘
	SetSystemTray(app, iconFS)
	// Create a new window with the necessary options.
	// 'Title' is the title of the window.
	// 'Mac' options tailor the window when running on macOS.
	// 'BackgroundColour' is the background colour of the window.
	// 'URL' is the URL that will be loaded into the webview.
	app.Window.NewWithOptions(application.WebviewWindowOptions{
		Title:     "Slapp3",
		Frameless: true,
		Mac: application.MacWindow{
			InvisibleTitleBarHeight: 50,
			Backdrop:                application.MacBackdropTranslucent,
			TitleBar:                application.MacTitleBarHiddenInset,
		},
		BackgroundColour: application.NewRGB(255, 255, 255),
		URL:              "/",
	})
	// Stated application event handlers.
	app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(e *application.ApplicationEvent) {
		appSev.SendNotification("application_started", "欢迎使用 Slapp3", "您的安全链接客户端已启动", nil, "MESSAGE_CATEGORY")
	})
	// Run the application. This blocks until the application has been exited.
	err := app.Run()

	// If an error occurred while running the application, log it and exit.
	if err != nil {
		log.Fatal(err)
	}
}

var rootCmd = &cobra.Command{
	Use:   "SLApp3",
	Short: "SLApp3 is a simple client for Secure Link",
	Long:  `SLApp3 is a simple client for Secure Link`,
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of SLApp3",
	Long:  `All software has versions. This is SLApp3's`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("SLApp version %s\n", Version)
	},
}

var connectCmd = &cobra.Command{
	Use:   "test-connect",
	Short: "Test the connection to the SLApp server",
	Long:  `This command tests the connection to the SLApp server and prints the result.`,
	Run: func(cmd *cobra.Command, args []string) {
		backend.TestConnect(Version)
	},
}

func main() {
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(connectCmd)
	// 添加以下逻辑：无参数时直接执行 Desktop()
	if len(os.Args) == 1 {
		Desktop()
		return
	}
	if err := rootCmd.Execute(); err != nil {
		println("Error:", err.Error())
	}
}
